<?php
/**
 * WithdrawModel.class.php
 * 用户提现模型
 *
 * @author  王中艺
 * @date    2016-11-22
 */

namespace Wechat\Model;

class WithdrawModel extends BaseModel{

    //重定义数据表明
    protected   $trueTableName  = 't_withdraw';

    /**
     * 用户提现
     * @param   $userId     用户ID
     * @param   $amount     提现金额
     * @param   $userInfo
     */
    function withdraw($userId, $amount){
        $userInfo   = D('User')->getUserInfo($userId);
        if($userInfo['wallet'] < $amount){
            $this->errMsg   = '余额不足!';
            return false;
        }

        $where  = sprintf(
            'user_id = %d and status != 0 and create_time >= %d and create_time <= %d',
            $userId, strtotime(date('Y-m-1')), time()
        );
        $wdCount    = $this->where($where)->count();
        if($wdCount >= 3){
            $this->errMsg   = '本月提现次数不足!';
            return false;
        }
        
        //提现目标确认
        $roleId     = $userInfo['role_id'];
        if($roleId >= 104){
            $this->errMsg   = '该角色无法提现!';
            return false;
        }
        if($roleId == 103){
            $targetId   = M('t_user_relative', null)
                ->where('user_id = %d', $userId)
                ->getField('dean_id');
            $targetId   = $targetId > 0 ? $targetId : 0;
        }else{
            $targetId   = 0;
        }

        
        $wdInfo     = array(
            'user_id'   => $userId,
            'amount'    => $amount,
            'create_time'   => time(),
            'target_id' => $targetId,
            'status'    => 2
        );

        $this->startTrans();
        if(!$this->add($wdInfo)){
            $this->rollback();
            $this->errMsg   = '提现信息写入失败!';
            return false;
        }

        //减去用户钱包金额
        $userInfo['wallet'] -= $amount;
        if(!D('User')->updateUserInfo($userInfo['id'], $userInfo)){
            $this->rollback();
            $this->errMsg   = '用户信息更新失败';
            return false;
        }

        $this->commit();
        return $userInfo;
    }

    /**
     * 用户提现记录
     * @param   $userId
     * @param   $page
     * @return  $list
     */
    function withdrawLog($userId, $page){
        $list   = $this->where('user_id = %d', $userId)
            ->order('id desc')
            ->page($page, C('PAGE_COUNT'))
            ->cache(true)
            ->select();

        foreach($list as &$val){
            $val['create_date']     = date('Y-m-d H:i:s', $val['create_time']);
            $val['status_text']     = C('WITHDRAW_STATUS.'.$val['status']);  
        }

        return $list;
    }
}